package com.example.search.listener;

import com.alibaba.fastjson.JSON;
import com.example.common.constants.ArticleConstants;
import com.example.model.search.pojo.SearchArticleVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class SyncArticleListener {
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @KafkaListener(topics = ArticleConstants.TOPIC_SYNC_ES)
    public void onMessage(String message) {
        log.info("收到文章同步消息：{}", message);
        try {
            SearchArticleVo searchArticleVo = JSON.parseObject(message, SearchArticleVo.class);
            IndexQuery indexQuery = new IndexQueryBuilder()
                    .withIndex("app_info_article")
                    .withId(searchArticleVo.getArticleId() + "")
                    .withSource(JSON.toJSONString(searchArticleVo)).build();
            elasticsearchTemplate.index(indexQuery, elasticsearchTemplate.getIndexCoordinatesFor(SearchArticleVo.class));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("文章同步失败：{}", e);
        }
    }
}
